<template>
  <view class="container">
    <view class="auth-header">
      <view class="auth-logo">
        <image :src="src" mode=""></image>
      </view>
    </view>

    <view class="auth-box">
      <!-- 登录方式选择 -->
      <!-- <view class="mode-section">
        <u-subsection class="subsection" mode="subsection" fontSize="15" :list="loginModeList" :current="currentModeIndex" @change="handleModeChange"></u-subsection>
      </view> -->
      <u-gap height="40"></u-gap>
      <view class="contents">
        <view class="c-left">
          <u-radio-group v-model="radiovalue1" placement="column" @change="groupChange">
            <u-radio label="登录代表您已同意" labelSize="15" name="登录代表您已同意" @change="radioChange">
              登录代表您已同意
              <text class="color-bs f-weight" @click="clickNotice(1)">用户协议</text>、 <text
                class="color-bs f-weight" @click="clickNotice(2)">隐私权政策</text>
            </u-radio>

          </u-radio-group>
          <!--        <view class="login-text">-->
          <!--          <text class="color-bs f-weight" @click="clickNotice(1)">用户协议</text>、 <text class="color-bs f-weight" @click="clickNotice(2)">隐私权政策</text>-->
          <!--        </view>-->
        </view>
        <!--      <view class="login-text">-->
        <!--        <text class="color-bs f-weight" @click="clickNotice(1)">用户协议</text>、 <text class="color-bs f-weight" @click="clickNotice(2)">隐私权政策</text>-->
        <!--      </view>-->
      </view>
      <!-- 登录表单 -->
      <u--form labelPosition="left" :model="formData" :rules="rules" ref="form">
        <view class="btn-group">
          <button class="auth-btn bg" type="default" open-type="getPhoneNumber"
                  @getphonenumber="getPhoneNumber">一键登录</button>
        </view>
      </u--form>
    </view>
  </view>
</template>

<script>
import {
  log,
  getUser
} from '../../api/login.js'
import {getUserInfo} from "../../api/setting";
import config from '@/common/config'
export default {
  data() {
    return {
      consent: false,
      currentModeIndex: 0,
      loginModeList: ['密码登录', '验证码登录'],
      inputType: 'password',
      codeDisabled: false,
      codeTips: '',
      src: config.baseImgUrl + '/minis/logo/hutai.png',
      formData: {
        mobile: '15896325478',
        password: '546648',
        code: ''
      },
      rules: {
        mobile: [{
          type: 'integer',
          required: true,
          message: '请填写手机号',
          trigger: ['blur', 'change']
        },
          {
            // 自定义验证函数，见上说明
            validator: (rule, value, callback) => {
              // 上面有说，返回true表示校验通过，返回false表示不通过
              // uni.$u.test.mobile()就是返回true或者false的
              return uni.$u.test.mobile(value)
            },
            message: '手机号码不正确',
            // 触发器可以同时用blur和change
            trigger: ['change', 'blur']
          }
        ],
        password: {
          type: 'string',
          min: 4,
          max: 16,
          required: true,
          message: '密码长度4-16位密码',
          trigger: ['blur', 'change']
        },
        code: {
          type: 'integer',
          len: 4,
          required: true,
          message: '请填写4位验证码',
          trigger: ['blur', 'change']
        }
      }
    }
  },
  onLoad() {
    this.login()
  },
  onReady() {

  },
  methods: {
    // 登录
    login() {
      uni.login({
        provider: 'weixin',
        success: (res) => {

        },
        fail: () => {
          uni.showToast({
            title: "微信登录授权失败",
            icon: "none"
          });
        }
      })
    },
    clickNotice(i) {
      if (i == 1) {
        uni.navigateTo({
          url: "/pages/setting/agreement?id=1"
        })
      }
      if (i == 2) {
        uni.navigateTo({
          url: "/pages/setting/privacyPolicy?id=2"
        })
      }
    },
    //获取手机code
    getPhoneNumber(e) {
      const c = this.consent

      if (c) {
        if (e.detail.code) {
          this.miniLogin(e.detail.code)
        }
      } else {
        uni.$u.toast("请勾选您已同意用户协议！")
      }

    },
    //登录
    miniLogin(phoneCode) {
      let that = this
      uni.showModal({
        mask: true,
        title: '授权登录',
        content: '授权微信登录，使用更多功能！',
        success(ress) {
          if (ress.confirm) {
            uni.getUserProfile({
              desc: '获取你的昵称，头像',
              success(userRes) {
                if (userRes.errMsg == 'getUserProfile:ok' && userRes.userInfo !=
                    undefined) {
                  let userinfo = userRes.userInfo
                  uni.login({
                    provider: 'weixin',
                    success(res) {
                      let parmas = {
                        encryptedData: '',
                        iv: '',
                        loginCode: res.code,
                        phoneCode: phoneCode,
                        signature: userRes.signature
                      }
                      log(parmas).then(loginRes => {
                        if (loginRes.code == 0) {
                          // that.$store.commit('setToken',loginRes.data.accessToken)
                          uni.setStorageSync('token',
                              loginRes.data.accessToken)
                        }
                      }).then(loginResT => {
                        getUser().then(infoRes => {
                          if (infoRes.code == 0) {
                            // 如果是扫码绑定 进来登录，需要跳转到绑定页面
                            const scene = uni.getStorageSync('loginScene');
                            if(scene){
                              uni.setStorageSync('loginScene', '')
                              uni.navigateTo({
                                url: "/pages/index/binding?scene=" + `${encodeURIComponent(scene)}`
                              })
                            }else{
                              getUserInfo().then(res => { //取实时
                                uni.setStorageSync('userInfo',res.data)
                              })
                              setTimeout(() => {
                                uni.switchTab({
                                  url: '/pages/index/index'
                                })
                              }, 1000)
                            }

                          }
                        })
                      })
                    }
                  })
                }
              },
            })
          }
        }
      })
    },
    groupChange(n) {
      console.log(n)
    },
    radioChange(n) {
      console.log(n)
      this.consent = true
    },
    handleModeChange(index) {
      if (index !== this.currentModeIndex) {
        this.currentModeIndex = index
        this.$refs.form.clearValidate()
      }
    },
    codeChange(text) {
      this.codeTips = text
    },
    getCode() {
      const mobile = this.formData.mobile
      if (!mobile) {
        uni.$u.toast('请填写手机号')
      } else if (!uni.$u.test.mobile(mobile)) {
        uni.$u.toast('手机号格式不正确')
      } else if (this.$refs.uCode.canGetCode) {
        // 模拟向后端请求验证码
        uni.showLoading({
          title: '正在获取验证码'
        })

        //scene:1登陆获取验证码场景
        sendSmsCode({
          mobile: mobile,
          scene: 1
        }).then(res => {
          //console.log(res)
          uni.hideLoading()
          uni.$u.toast('验证码已发送')
          // 通知验证码组件内部开始倒计时
          this.$refs.uCode.start()
        })
      } else {
        uni.$u.toast('倒计时结束后再发送')
      }
    },
    handleSubmit() {
      this.$refs.form.validate().then(res => {
        uni.login({
          provider: 'weixin',
          success: res => {
            let data = this.formData
            data.socialType = null //WECHAT_MINI_APP 先指定固定值
            data.socialCode = res.code
            data.socialState = Math.random() // 该参数没有实际意义暂时传随机数
            this.mobileLogin(data)
          },
          fail: res => {
            this.mobileLogin(this.formData)
          }
        })
      })
    },
    mobileLogin(data) {
      // this.$store.dispatch('Login', { type: this.currentModeIndex, data: data }).then(res => {
      uni.$u.toast('登录成功')
      this.$store.commit('setRoleId', 0)
      setTimeout(() => {
        uni.switchTab({
          url: '/pages/index/index'
        })
      }, 300)
      // })
    }
  }
}
</script>

<style lang="scss" scoped>
.auth-header {
  height: 400rpx;
  @include flex-center;

  .auth-logo {
    image {
      width: 250rpx;
      height: 150rpx;
    }
  }
}

.contents {
  text-align: center;
}

.c-left {
  float: left
}

.login-text {
  float: left;
  font-size: 26rpx;
}

.auth-box {
  @include flex-center(column);

  .mode-section {
    width: 600rpx;

    .subsection {
      height: 60rpx;
    }
  }

  .btn-group {
    width: 600rpx;

    .auth-btn {
      line-height: 90rpx;
      font-size: 32rpx;
    }

    .bg {
      background-color: #4e5ff9;
      color: #fff;
      font-size: 14px;
      margin-top: 40rpx;
    }
  }
}
</style>